package extractor;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import db.QueryPool;

public class TweetGen {
	private String keyword = "";
	private String state = "";
	private String maxid = "";
	private String geocode ="";
	private String formalMaxID;
	QueryPool query = new QueryPool();
	
	private HashMap<String, String> map = new HashMap();
	
	public TweetGen(String keyword, String formalMaxID, String state, String geocode) {
		this.keyword = keyword;
		this.formalMaxID = formalMaxID;
		this.state = state;
		this.geocode = geocode;
	}
	
	public HashMap getTwitterMessage() throws InterruptedException, ClassNotFoundException, SQLException {
		for (int i = 1; i < 11; i++) {
			genTweets(keyword, i);
			//System.out.println(" number : " + i);
		}
		return map;
	}
	
	public void genTweets(String keyword, int i) throws InterruptedException, ClassNotFoundException, SQLException {
		ArrayList array = new ArrayList();
        String requestUrl = "http://search.twitter.com/search.json?q=" + keyword + "&lang=en&result_type=recent&count=100&page="+i+"&geocode=" + geocode;
        if (formalMaxID !=null) requestUrl = requestUrl + "&since_id="+ formalMaxID;
        
        //System.out.println(requestUrl);
        String inputLine, result = "";
        
        try {
            URL url = new URL(requestUrl.toString());
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            
            while ((inputLine = in.readLine()) != null) {
                result = result.concat(inputLine);
            }
        } catch (Exception e) {
        	
        }
		
        Analyzer analyzer = new Analyzer();
		if ("".equals(result) || result != null) {
			if ("".equals(maxid)) maxid = extractMaxID(result);
		} else {
			System.out.println("the result from twitter is null");
		}
		
		array = analyzer.fromJSONObjectToString(result);
		String time = "";
		String message = "";
		String tp = "";
		
		if (array != null) {
			for (int j = 0; j < array.size(); j++) {
				
				tp = ((String) array.get(j));
				time = tp.substring(0,tp.indexOf("$$$"));
				message = tp.substring(tp.indexOf("$$$")+3 , tp.length());
				
				query.insertTwitter(keyword, time, maxid, state, message);
			}
		}
	}

	private String extractMaxID(String tweet) {
		String result = "";
		if (tweet.length() >= 13) {
			result = tweet.substring(tweet.indexOf("\"max_id\":") + 9 , tweet.indexOf(",\"max_id_str\""));
			//System.out.println(result);
		}
		return result;
	}
}
